<template>
  <div class='container-questionNew'>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{formData.id ? '试题修改' : '试题录入' }}</span>
        <!-- <button @click="getQuesDetail">模拟跳转</button> -->
      </div>
      <el-form label-position="right" label-width="100px" :model="formData" :rules="rules" ref="ruleForm">
        <el-form-item label="学科:" prop="subjectID">
          <el-select v-model="formData.subjectID"
            placeholder="请选择"
            size="small"
            style="width: 400px;"
            clearable
            @change="subChange">
            <el-option
              v-for="item in subList"
              :key="item.id"
              :label="item.subjectName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- prop="catalogID" -->
        <el-form-item label="目录:" prop="catalogID">
          <el-select v-model="directoryName"
            placeholder="请选择"
            size="small"
            style="width: 400px;"
            clearable>
            <el-option
              v-for="(item, idx) in selecDirectory"
              :key="idx"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select v-model="formData.enterpriseID"
            placeholder="请选择"
            size="small"
            style="width: 400px;"
            clearable>
            <el-option
              v-for="item in compList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:">
          <el-form-item prop="province">
            <el-select v-model="formData.province"
              placeholder="请选择"
              size="small"
              style="width: 200px;"
              @clear="cityChange"
              clearable>
              <el-option
                v-for="(item, idx) in citySelect.province"
                :key="idx"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="city">
            <el-select v-model="formData.city"
              placeholder="请选择"
              size="small"
              style="width: 200px;"
              clearable>
              <el-option
                v-for="(item, idx) in citySelect.cityDate"
                :key="idx"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="方向:" prop="direction">
          <el-select v-model="formData.direction"
            placeholder="请选择"
            size="small"
            style="width: 400px;"
            clearable>
            <el-option
              v-for="(item, idx) in direction"
              :key="idx"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型:">
          <el-radio-group v-model="formData.questionType">
            <el-radio :label="item.value.toString()"
             v-for="item in questionType"
             :key="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:">
          <el-radio-group v-model="formData.difficulty">
            <el-radio :label="item.value.toString()"
              v-for="item in difficulty"
              :key="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干:" prop="question">
          <quillEditor
            v-model="formData.question"
            :options="editorOption"
          >
          </quillEditor>
        </el-form-item>
        <!-- label="选项:" -->
        <el-form-item label="选项:"
          v-if="formData.questionType !== '3'"
        >
          <div
            class="optionStyle"
            v-for="(item, idx) in formData.options"
            :key="idx"
          >
            <el-radio v-if="formData.questionType==='1'" v-model="singleRadio" :label="item.code" @change="singleChoose(item)">
              {{item.code}}:
              <el-input
                style="width: 200px;margin-bottom: 20px;"
                v-model="item.title">
              </el-input>
            </el-radio>
            <el-checkbox v-if="formData.questionType==='2'" v-model="item.isRight">
              {{item.code}}:
              <el-input
                style="width: 200px;margin-bottom: 20px;"
                v-model="item.title">
              </el-input>
            </el-checkbox>
            <input type="file" ref="fileElem" @change="hFiles(idx)" hidden />
            <img :src="item.img || imgUrl" @click="clickImg(idx)" class="img" />
            <i class="el-icon-close" @click="delImg(idx)"></i>
          </div>
          <el-button type="danger"
            v-show="formData.questionType !== '3'"
            :disabled="formData.questionType!=='2'"
            @click="addOption"
          >
            +增加选项与答案
          </el-button>
        </el-form-item>
        <el-form-item label="解析视频:" prop="videoURL">
          <el-input style="width: 400px;" v-model="formData.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析:" prop="answer">
          <quillEditor
            class="clearfix"
            v-model="formData.answer"
            :options="editorOption"
          >
          </quillEditor>
        </el-form-item>
        <el-form-item label="题目备注:" prop="remarks">
            <!-- v-model="textarea" -->
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            style="width: 400px;"
            v-model="formData.remarks"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="试题标签:">
          <el-select v-model="tagsValue"
            placeholder="请选择"
            size="small"
            style="width: 400px;"
            clearable
            multiple>
            <el-option
              v-for="(item, idx) in selecTags"
              :key="idx"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary"
            @click="submit"
            v-if="!formData.id"
            size="small"
          >
            确认提交
          </el-button>
          <el-button type="success"
            @click="saveChange"
            v-if="formData.id"
            size="small"
          >
            保存修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { list as subjectList } from '@/api/hmmm/subjects'
import { list as companyList } from '@/api/hmmm/companys'
import { list as direcList } from '@/api/hmmm/directorys'
import { list as getTags } from '@/api/hmmm/tags'
import { detail as quesDetail, add, update } from '@/api/hmmm/questions'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
import defaultImg from '@/assets/1.jpg'
export default {
  name: 'QuestionNew',
  components: {
    quillEditor
  },
  data () {
    return {
      imgUrl: defaultImg,
      directoryName: '',
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'blur' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ]
      },
      // 表单数据
      formData: {
        id: '',
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市i
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [{
          code: 'A',
          title: '',
          img: '',
          isRight: 1
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: 0
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: 0
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: 0
        }], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      tagsValue: [],
      singleRadio: 'A',
      // 富文本设置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },
      subList: [], // 学科列表
      compList: [], // 公司列表
      directoryList: [], // 目录列表
      tagsList: [], // 标签列表
      citySelect: {
        province: [], // 城市数据
        cityDate: [] // 选中城市后的地区数据
      },
      selecDirectory: [], // 联动学科目录数据
      selecTags: [], // 联动学科标签数据
      direction, // 以下为三个常量
      questionType,
      difficulty
    }
  },
  created () {
    this.initData()
    this.getQuesDetail()
  },
  methods: {
    delImg (idx) {
      this.formData.options.forEach((item, index) => {
        if (idx === index) {
          item.img = ''
        }
      })
    },
    hFiles (idx) {
      const files = this.$refs.fileElem[idx].files
      if (files.length) {
        this.formData.options.forEach((item, index) => {
          if (idx === index) {
            item.img = URL.createObjectURL(files[0])
          }
        })
      }
    },
    clickImg (idx) {
      this.$refs.fileElem[idx].click()
    },
    cityChange () {
      this.formData.city = ''
    },
    async saveChange () {
      if (this.multiSelect) {
        try {
          await update(this.formData)
          this.$message.success('修改成功')
          this.$router.back()
        } catch (err) {
          this.$message.error('修改失败')
          console.log(err)
        }
      } else {
        this.$message.error('请至少选择两个选项')
      }
    },
    submit () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // 如果是多选的情况必须选择两个以上选项
          if (this.multiSelect) {
            try {
              await add(this.formData)
              this.$message.success('录入成功')
              this.$router.push('/questions/list')
            } catch (err) {
              this.$message.error('录入失败')
              console.log(err)
            }
          } else {
            this.$message.error('请至少选择两个选项')
          }
        }
      })
    },
    singleChoose (val) {
      this.formData.options.forEach(item => {
        item.isRight = item === val ? 1 : 0
      })
    },
    addOption () {
      let max
      if (this.formData.options.length === 4) {
        // eslint-disable-next-line no-prototype-builtins
        if (this.formData.options[0].hasOwnProperty('id')) {
          this.formData.options.forEach(item => {
            max = Math.max(item.id) + 1
          })
          this.formData.options.push({
            code: 'E',
            title: '',
            img: '',
            isRight: 0,
            id: max
          })
        } else {
          this.formData.options.push({
            code: 'E',
            title: '',
            img: '',
            isRight: 0
          })
        }
      }
    },
    // 根据id跳转到编辑页面 初始化渲染
    async getQuesDetail () {
      if (this.$route.query.id) {
        const { data: res } = await quesDetail({
          id: this.$route.query.id
        })
        const { answer, city, direction, province, difficulty, subjectID, question, questionType, enterpriseID, remarks, videoURL } = res
        Object.assign(this.formData, { answer, city, direction, province, difficulty, subjectID, question, questionType, enterpriseID, remarks, videoURL })
        this.name = res.subjectName
        this.directoryName = res.directoryName
        this.tagsValue = res.tags.split(',')
        this.formData.id = parseInt(this.$route.query.id)
        this.formData.options = res.options.map(item => {
          delete item.questionsID
          item.code = item.code.charCodeAt()
          item.isRight = !!item.isRight
          return item
        })
        this.formData.options.sort(function (a, b) {
          return (a.code - b.code)
        })
        this.formData.options.forEach(item => {
          item.code = String.fromCharCode(item.code)
        })
        if (res.questionType === '1') {
          this.formData.options.forEach(item => {
            if (item.isRight === true) {
              this.singleRadio = item.code
            }
          })
        }
        this.formData.addDate = new Date()
        this.formData.creatorID = '2'
        this.directoryList.forEach(val => {
          if (val.subjectName === this.name) {
            this.selecDirectory.push({
              id: val.id,
              name: val.directoryName
            })
          }
        })
        this.tagsList.forEach(value => {
          if (value.subjectName === this.name) {
            this.selecTags.push(value.tagName)
          }
        })
      }
    },
    // 初始化数据
    initData () {
      const data = {
        page: 1,
        pagesize: 20
      }
      this.getSubjectList(data)
      this.getCompanyList(data)
      this.getDirecList(data)
      this.getTags(data)
      this.getProvince()
    },
    // 获取学科数据
    async getSubjectList (data) {
      const { data: res } = await subjectList(data)
      this.subList = res.items
      // console.log(res)
    },
    // 获取企业数据
    async getCompanyList (data) {
      const { data: res } = await companyList(data)
      this.compList = res.items
    },
    // 获取目录数据
    async getDirecList (data) {
      const { data: res } = await direcList(data)
      // console.log(res)
      this.directoryList = res.items
    },
    // 获取标签数据
    async getTags (data) {
      const { data: res } = await getTags(data)
      // console.log(res)
      this.tagsList = res.items
    },
    // 获取城市数据
    getProvince () {
      this.citySelect.province = provinces()
    },
    subChange () {
      this.directoryName = ''
      this.tagsValue = []
      this.selecDirectory = []
      this.selecTags = []
      this.subList.forEach(item => {
        if (item.id === this.formData.subjectID) {
          this.directoryList.forEach(val => {
            if (val.subjectName === item.subjectName) {
              this.selecDirectory.push({
                id: val.id,
                name: val.directoryName
              })
            }
          })
          this.tagsList.forEach(value => {
            if (value.subjectName === item.subjectName) {
              this.selecTags.push(value.tagName)
            }
          })
        }
      })
    }
  },
  computed: {
    multiSelect () {
      let sum = 0
      this.formData.options.forEach(item => {
        sum += item.isRight
      })
      return this.formData.questionType === '2' ? !(sum <= 1) : true
    },
    Seltags () {
      return this.tagsValue.join()
    }
  },
  watch: {
    // 监听城市数据选择后 渲染地区列表
    'formData.province': function () {
      this.citySelect.cityDate = citys(this.formData.province)
    },
    Seltags: function () {
      this.formData.tags = this.Seltags
    },
    directoryName: function () {
      this.directoryList.forEach(item => {
        if (item.directoryName === this.directoryName) {
          this.formData.catalogID = item.id
        }
      })
    }
    // '$route' (to, from) {
    //   if (to.fullPath === '/questions/new') this.$refs.ruleForm.resetFields()
    // }
  },
  beforeRouteUpdate (to, from, next) {
    if (to.fullPath === '/questions/new') {
      this.$refs.ruleForm.resetFields()
      this.directoryName = ''
      this.singleRadio = 'A'
      this.tagsValue = []
      this.selecDirectory = []
      this.selecTags = []
      this.formData.id = ''
      this.formData.addDate = ''
      this.formData.questionType = '1'
      this.formData.difficulty = '1'
      this.formData.options = [{
        code: 'A',
        title: '',
        img: '',
        isRight: 1
      },
      {
        code: 'B',
        title: '',
        img: '',
        isRight: 0
      },
      {
        code: 'C',
        title: '',
        img: '',
        isRight: 0
      },
      {
        code: 'D',
        title: '',
        img: '',
        isRight: 0
      }]
    }
    next()
  }
}
</script>

<style scoped>
  .el-icon-close {
    position: relative;
    top: -54px;
    left: 353px;
    color: red;
  }
  .img {
    position: absolute;
    left: 260px;
    top: -5px;
    width: 100px;
    height: 50px;
    border: 1px solid #000;
  }
  .el-form-item .el-form-item {
    float: left;
  }
  .parent {
    position: relative;
    display: inline-block;
  }
  .dele {
  position: absolute;
  right: -10px;
  top: -10px;
  }
  .el-image {
    border: 1px solid #000;
    width: 100px;
    height: 50px;
    vertical-align: middle;
  }
  /deep/.ql-editor {
    height: 300px;
  }
  .optionStyle {
    position: relative;
    display: flex;
    flex-direction: column;
  }
</style>
